package com.spice.im.chat;


import java.io.ByteArrayOutputStream;





import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jivesoftware.smack.util.StringUtils;











import com.dodola.model.DuitangInfo;
import com.dodola.model.DuitangInfoAdapter;
import com.dodowaterfall.widget.FlowView;
//import com.example.android.bitmapfun.util.AsyncTask;
import com.beem.push.utils.AsyncTask;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.spice.im.FlippingLoadingDialog;
import com.spice.im.R;
import com.spice.im.RoundImageView;
import com.spice.im.SimpleListDialog;
import com.spice.im.SimpleListDialogAdapter;
import com.spice.im.SpiceApplication;
import com.spice.im.SimpleListDialog.onSimpleListItemClickListener;
import com.spice.im.chat.ChatPullRefListActivity.StaggeredAdapter;
import com.spice.im.chat.MessageText.MESSAGE_TYPE;
import com.spice.im.ui.HandyTextView;
import com.spice.im.utils.ImageFetcher;
import com.spiceim.db.TContactGroup;
import com.spiceim.db.TContactGroupAdapter;
import com.stb.isharemessage.BeemService;
import com.stb.isharemessage.service.XmppConnectionAdapter;
//import com.immomo.momo.android.util.PhotoUtils;
//import com.immomo.momo.android.entity.Message.MESSAGE_TYPE;
//import com.immomo.momo.android.view.HandyTextView;

//import com.immomo.momo.android.activity.R;

//import com.stb.isharemessage.ui.ChatActivity.MessageText;










import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class VideoMessageItem implements OnLongClickListener, OnClickListener{
	private static final String TAG = "VideoMessageItem > DeleteMessage";
	private RoundImageView mIvImage;
	private LinearLayout mLayoutLoading;
	private ImageView mIvLoading;
	private HandyTextView mHtvLoadingText;

	private AnimationDrawable mAnimation;
	private int mProgress;
	private Bitmap mBitmap;
	protected Context mContext;
	
	private MESSAGE_TYPE messageType;
	
	protected LayoutInflater mInflater;
	/**
	 * MessageContainer
	 */
	protected LinearLayout mLayoutMessageContainer;
	protected View mRootView;
	protected int mBackground;
	private MessageText mMsgText;
//	private ImageFetcher mImageFetcher;
	
	
	
	private HttpUtils http;
	private HttpHandler handler;
//	private LinearLayout mLayoutLoading;
//	private ImageView mIvLoading;
//	private HandyTextView mHtvLoadingText;
//
//	private AnimationDrawable mAnimation;
//	private int mProgress;
	private static final String PHOTOPATH2 = "beemphoto";
	private String mRecordPath;// 视频的存储名称
	private float mRecord_Time;// 视频的时间
	private int mPosition;
	private StaggeredAdapter mStAdapter = null;
	private String fromAccount;
	private String toAccount;
	private ArrayList mGroupMsgRecipient = null;//群发消息接收人
	
	private int chattype = 0;//0 单聊 1 群聊自己发送消息 2 群聊接收他人消息
	private String path = "";
	
	private String headimg = "",myheadimg = "";
	private ChatPullRefListActivity mActivity = null;
	private String username = "",myusername = "";
	private HandyTextView message_tv_status_audio = null;//消息发送状态
	private LinearLayout mLayoutLeftContainer;
	private FlowView mIvPhotoView;
	
	private HandyTextView message_tv_timestamp;//消息发送/接收时间
	private HandyTextView message_tv_nickname;
	
	private DuitangInfo duitangInfo = null;
	private DuitangInfoAdapter duitangInfoAdapter = null;//用户信息存入本地数据库
	private TContactGroupAdapter tContactGroupAdapter = null;
	private TContactGroup tg = null;
	private SimpleListDialog mDialog = null;
	private MessageAdapter messageAdapter = null;//删除本地数据库用户聊天记录
	//no enclosing instance of type is available due to some intermediate constructor invocation
//    public ImageMessageItem(ChatActivity wp,final String bareJid, final String name, final String message, final boolean isError,
//    	    final Date date) {//添加的  
//        wp.super(bareJid, name, message, isError,date);  
//    } 
//MessageText(final String bareJid, final String name, final String message, final boolean isError,final Date date)
	public VideoMessageItem(Context context,
			MessageText msgText,
			int position,
			StaggeredAdapter stAdapter,
			String _fromAccount,
			String _toAccount,
			ArrayList groupMsgRecipient,
			String _headimg,
			String _myheadimg,
			ChatPullRefListActivity activity,
			String _username,
			String _myusername){
//		super(bareJid, name, message, isError,date);
		mMsgText = msgText;
		mContext = context;
		mPosition = position;
		mStAdapter = stAdapter;
		fromAccount = _fromAccount;
		toAccount = _toAccount;
		mGroupMsgRecipient = groupMsgRecipient;
		headimg = _headimg;
		myheadimg = _myheadimg;
		mActivity = activity;
		username = _username;
		myusername = _myusername;
		//群聊：mMsgText.getBareJid()=20140508@conference.pc2011040521xsg/18901203590;fromAccount=18901203590@pc2011040521xsg/Beem;toAccount=20140508@conference.pc2011040521xsg
		//单聊：06-05 22:23:25.549: ERROR/※※※※※20140605(1)※※※※※(10831): ※※mMsgText.getBareJid()=Me;fromAccount=18901203590@pc2011040521xsg/Beem;toAccount=18901159737@pc2011040521xsg
		//单聊: 06-05 22:23:25.549: ERROR/※※※※※20140605(2)※※※※※(10831): ※※mMsgText.getBareJid()=;fromAccount=18901203590;toAccount=18901159737@pc2011040521xsg

		Log.e("※※※※※20140605(1)※※※※※", "※※mMsgText.getBareJid()="+mMsgText.getBareJid()+";fromAccount="+fromAccount+";toAccount="+toAccount);
		Log.e("※※※※※20140605(2)※※※※※", "※※mMsgText.getBareJid()="+StringUtils.parseResource(mMsgText.getBareJid())+";fromAccount="+StringUtils.parseName(fromAccount)+";toAccount="+toAccount);
		String temp2 = StringUtils.parseResource(mMsgText.getBareJid());
		if(temp2!=null && temp2.startsWith("/"))
			temp2 = temp2.substring(1);//"/3"
		if(StringUtils.parseResource(mMsgText.getBareJid())!=null 
				&& temp2.length()!=0
				&& !temp2.equalsIgnoreCase("Beem")
				&& temp2.equals(StringUtils.parseName(fromAccount)))
			chattype = 1;
		else if(StringUtils.parseResource(mMsgText.getBareJid())!=null 
				&& temp2.length()!=0
				&& !temp2.equalsIgnoreCase("Beem")
				&& !temp2.equals(StringUtils.parseName(fromAccount)))
			chattype = 2;
		else
			chattype = 0;
		
		duitangInfoAdapter = DuitangInfoAdapter.getInstance(mContext);
		tContactGroupAdapter = TContactGroupAdapter.getInstance(mContext);
		messageType = mMsgText.getMessageType();
		
//		initNameImg();
		
		//20121224 start
		messageAdapter = MessageAdapter.getInstance(mContext);
		mLoadingDialog = new FlippingLoadingDialog(mContext, "请求提交中");
		String[] codes = new String[] { "复制","删除","转发" };//分享,翻译
		mDialog = new SimpleListDialog(context);
		mDialog.setTitle("提示");
		mDialog.setTitleLineVisibility(View.GONE);
		mDialog.setAdapter(new SimpleListDialogAdapter(context, codes));
		mDialog.setOnSimpleListItemClickListener(new OnReplyDialogItemClickListener(
				));
		//20141224 end
		
		mInflater = LayoutInflater.from(context);
		switch (messageType) {
		case RECEIVER:
//			mRootView = mInflater.inflate(R.layout.specialchatting_item_to_picture,
//					null);
////			mBackground = R.drawable.bg_message_box_send;
			//message_send_template.xml
			mRootView = mInflater.inflate(R.layout.message_send_template,
					null);
			mBackground = R.drawable.bg_message_box_send;
			break;

		case SEND:
//			mRootView = mInflater.inflate(R.layout.specialchatting_item_from_picture,
//					null);
////			mBackground = R.drawable.bg_message_box_receive;
			//message_receive_template.xml
			mRootView = mInflater.inflate(R.layout.message_receive_template,
					null);
			mBackground = R.drawable.bg_message_box_receive;
			message_tv_status_audio = (HandyTextView)mRootView.findViewById(R.id.message_tv_status_audio);
			break;
		case conference:
//			mRootView = mInflater.inflate(R.layout.specialmultichatting_item_to_picture,
//					null);
////			mBackground = R.drawable.bg_message_box_receive;
			if(mMsgText.getBareJid().indexOf("@1")==-1){//自己发给群
				mRootView = mInflater.inflate(R.layout.message_receive_template,
						null);
				mBackground = R.drawable.bg_message_box_receive;
				message_tv_status_audio = (HandyTextView)mRootView.findViewById(R.id.message_tv_status_audio);
			}else{
				String key = StringUtils.parseResource(mMsgText.getBareJid());
				if(key!=null && key.startsWith("/"))
					key = key.substring(1);//"/18901203590"
				String key2 = StringUtils.parseName(fromAccount);
				if(key.equals(key2)){//自己发给群
					mRootView = mInflater.inflate(R.layout.message_receive_template,
							null);
					mBackground = R.drawable.bg_message_box_receive;
					message_tv_status_audio = (HandyTextView)mRootView.findViewById(R.id.message_tv_status_audio);
				}else{
					//message_send_template.xml
					mRootView = mInflater.inflate(R.layout.message_send_template,
							null);
					mBackground = R.drawable.bg_message_box_send;
					message_tv_status_audio = (HandyTextView)mRootView.findViewById(R.id.message_tv_status_audio);
				}
			}
			break;
		}

		if(msgText.getMessage().startsWith("<transferfile mode=")
				|| msgText.getMessage().startsWith("<transferfile transt='offline' mode=")){//文件
            // 首先匹配img标签内的内容
            String img_regex = "<(?i)transferfile(.*?)>(.*?)</(?i)transferfile>";//img
            Pattern p = Pattern.compile(img_regex);
            Matcher m = p.matcher(msgText.getMessage());
            
            String src_alt;
            String img_name;
            String src_type="";
            String filelength="";
            while(m.find()){

                src_alt=m.group(1);
                img_name=m.group(2);
                if(null==src_alt && null==img_name){
                    continue;
                }
                
                // 匹配src中的内容
                String src_reg = "mode=\'(.*?)\'";//src
                Pattern src_p = Pattern.compile(src_reg);
                Matcher src_m = src_p.matcher(src_alt);
                while(src_m.find()){
//                    System.out.println("mode是：" + src_m.group(1));
                }
                
                // 匹配alt中的内容
                String alt_reg = "type=\'(.*?)\'";//alt
                Pattern alt_p = Pattern.compile(alt_reg);
                Matcher alt_m = alt_p.matcher(src_alt);
                while(alt_m.find()){
//                    System.out.println("type是：" + alt_m.group(1));
                	src_type = alt_m.group(1);
                	 System.out.println("type是：" +src_type);

                }                
                // 匹配filelength中的内容
                String filelength_reg = "filelength=\'(.*?)\'";//alt
                Pattern filelength_p = Pattern.compile(filelength_reg);
                Matcher filelength_m = filelength_p.matcher(src_alt);
                while(filelength_m.find()){
                	filelength = filelength_m.group(1);
                	System.out.println("时长:"+filelength+"秒");//录音时长
                	
//                    System.out.println("filelength是：" + filelength_m.group(1));
//                    holder.text = (TextView) convertView.findViewById(R.id.chatting_content_itv);
//                    holder.contentView.setText("时长:"+filelength_m.group(1)+"秒");//录音时长
                } 
                
// 				File file = new File(img_name);
				String temp = img_name.substring(img_name.lastIndexOf(".")+1);
//				if( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && file.exists() &&
				if( //file.exists() &&		
						(temp.equalsIgnoreCase("jpg")
						|| temp.equalsIgnoreCase("png")
						|| temp.equalsIgnoreCase("gif")
						|| temp.equalsIgnoreCase("bmp"))){
				}else{
					//img,audio,video,other
					if(src_type.equals("audio")){//amr
						
					}else if(src_type.equals("video")){
						mRecordPath = img_name;//
						//服务器配置地址：http://10.0.2.2:8080/26/1507088640324.mp4
						//实际地址应该是：http://59.52.226.115:8189/javacenterhome/26/1507088640324.mp4
//						Toast.makeText(mContext, "视频000"+mRecordPath, Toast.LENGTH_SHORT).show(); 
						mRecord_Time = Float.valueOf(filelength);
					}else
						;
				}
            }
            
		}
//		if (mRootView != null) {
		mLayoutMessageContainer = (LinearLayout) mRootView
		.findViewById(R.id.message_layout_messagecontainer);
//		mLayoutMessageContainer.setBackgroundResource(mBackground);
		
		mLayoutLeftContainer = (LinearLayout) mRootView
		.findViewById(R.id.message_layout_leftcontainer);
		mIvPhotoView = (FlowView) mRootView.findViewById(R.id.message_iv_userphoto);
		
		message_tv_timestamp = (HandyTextView)mRootView.findViewById(R.id.message_tv_timestamp);
		message_tv_nickname = (HandyTextView)mRootView.findViewById(R.id.message_tv_nickname);
		
		onInitViews();
//		}
	}
	
	protected void onInitViews() {
		View view = mInflater.inflate(R.layout.message_video, null);
		mLayoutMessageContainer.addView(view);////////
		mIvImage = (RoundImageView) view.findViewById(R.id.message_iv_msgimage);
		mLayoutLoading = (LinearLayout) view
				.findViewById(R.id.message_layout_loading);
		mIvLoading = (ImageView) view.findViewById(R.id.message_iv_loading);
		mHtvLoadingText = (HandyTextView) view
				.findViewById(R.id.message_htv_loading_text);
		mIvImage.setOnClickListener(this);
		mIvImage.setOnLongClickListener(this);
		
		if(mMsgText.getIsOffline()==2){
//			mRootView.findViewById(R.id.isOfflineMsg).setVisibility(View.VISIBLE);
			
		    if(message_tv_status_audio!=null){
		    	message_tv_status_audio.setBackgroundResource(R.drawable.bg_msgbox_state_failure2);
		    	message_tv_status_audio.setText("发送失败");
		    }
		}else if(mMsgText.getIsOffline()==1){
//			mRootView.findViewById(R.id.isOfflineMsg).setVisibility(View.GONE);
		    if(message_tv_status_audio!=null){
		    	message_tv_status_audio.setBackgroundResource(R.drawable.bg_msgbox_state_read2);
		    	message_tv_status_audio.setText("送达");
		    }
		}else if(mMsgText.getIsOffline()==0){
//			mRootView.findViewById(R.id.isOfflineMsg).setVisibility(View.GONE);
		    if(message_tv_status_audio!=null){
		    	message_tv_status_audio.setBackgroundResource(R.drawable.bg_msgbox_state_read2);
		    	message_tv_status_audio.setText("发送中");
		    }
		}
		
//        mImageFetcher = new ImageFetcher(mContext, 77);
//        mImageFetcher.setUListype(0);
//        mImageFetcher.setLoadingImage(R.drawable.empty_photo3);//empty_photo3 video
//        mImageFetcher.setExitTasksEarly(false);
        
        if(mMsgText.getBareJid().indexOf("@1")!=-1){
			if(mRecordPath.lastIndexOf("/")!=-1)
				path = XmppConnectionAdapter.downloadPrefix+"/userfiles/"+StringUtils.parseResource(mMsgText.getBareJid())+"/"+mRecordPath.substring(mRecordPath.lastIndexOf("/")+1);
			else
				path = XmppConnectionAdapter.downloadPrefix+"/userfiles/"+StringUtils.parseResource(mMsgText.getBareJid())+"/"+mRecordPath;
        }else{
			if(mRecordPath.lastIndexOf("/")!=-1)
				path = XmppConnectionAdapter.downloadPrefix+"/userfiles/"+StringUtils.parseName(mMsgText.getBareJid())+"/"+mRecordPath.substring(mRecordPath.lastIndexOf("/")+1);
			else
				path = XmppConnectionAdapter.downloadPrefix+"/userfiles/"+StringUtils.parseName(mMsgText.getBareJid())+"/"+mRecordPath;
        }
		Log.e("※※※※※20140605(3)※※※※※", path);
		Log.e("※※※※※20140605(4)※※※※※", "chattype="+chattype);
			
//        if(chattype == 2)
		String key = StringUtils.parseResource(mMsgText.getBareJid());
		if(key!=null && key.startsWith("/"))
			key = key.substring(1);//"/18901203590"
		String key2 = StringUtils.parseName(fromAccount);
		
			
		if(messageType!=MESSAGE_TYPE.SEND
				&& !(messageType==MESSAGE_TYPE.conference 
				     && 
				     (
//				    		 (mMsgText.getBareJid().indexOf("@1")==-1)
//				    		 ||
				    		 (key.equals(key2))
				     )
				   ))
        	mRecordPath = path;
		
//		Toast.makeText(mContext, "视频111"+mRecordPath, Toast.LENGTH_SHORT).show(); 
        
	}
	private String tempdownsavepath = "";
	String headpath = "";
	protected void onFillMessage() {
		
		mLayoutLeftContainer.setVisibility(View.VISIBLE);
//		mIvPhotoView.setImageBitmap();
//		mIvPhotoView.setImageResource(R.drawable.head);
		switch (messageType) {
			case RECEIVER:
//				mImageFetcher.loadImage(headimg, mIvPhotoView);
//				message_tv_nickname.setText(username);
				if(mMsgText.getBareJid().indexOf("@1")==-1){
//	        		try{
//	        			headpath = "data/avatar/"+avatar_file(Integer.parseInt(StringUtils.parseName(mMsgText.getBareJid())),"middle","");
//	        		}catch(Exception e){
//	        			e.printStackTrace();
//	        		}
//	        		if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()))!=null){
//	        			headpath = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getAvatarPath();
//						if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName()!=null && tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName().length()!=0)
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName());
//						else
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getUsername());
//	        		}else{
//	        			headpath = "";
//	        			message_tv_nickname.setText(mMsgText.getBareJid());
//	        		}
					
					tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()));
					if(tg!=null){
						headpath = tg.getAvatarPath();
						if(tg.getName()!=null && tg.getName().length()!=0)
							message_tv_nickname.setText(tg.getName());
						else
							message_tv_nickname.setText(tg.getUsername());
					}else{
						headpath = "";
						message_tv_nickname.setText(mMsgText.getBareJid());
					}
				}else{
					String key = StringUtils.parseResource(mMsgText.getBareJid());
					if(key!=null && key.startsWith("/"))
						key = key.substring(1);//"/18901203590"
					
//	        		try{
//	        			headpath = "data/avatar/"+avatar_file(Integer.parseInt(key),"middle","");
//	        		}catch(Exception e){
//	        			e.printStackTrace();
//	        		}
////					message_tv_nickname.setText("uid为"+key);
////					message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress("2@0")).getName());
//	        		if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"))!=null){
//	        			headpath = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getAvatarPath();
//						if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName()!=null && tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName().length()!=0)
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName());//bug 需要登录成功后将自己的信息存入本地数据库
//						else
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getUsername());
//	        		}else{
//	        			headpath = "";
//	        			message_tv_nickname.setText(key+"@0");
//	        		}
					
					tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"));
					if(tg!=null){
						headpath = tg.getAvatarPath();
						if(tg.getName()!=null && tg.getName().length()!=0)
							message_tv_nickname.setText(tg.getName());
						else
							message_tv_nickname.setText(tg.getUsername());
					}else{
						headpath = "";
						message_tv_nickname.setText(StringUtils.parseBareAddress(key+"@0"));//"空"+
					}
				}
//				mImageFetcher.loadImage(XmppConnectionAdapter.downloadPrefix+headpath, mIvPhotoView);
				if(headpath!=null
	    	    		&& headpath.length()!=0
	    	    		&& !headpath.equalsIgnoreCase("null"))
//	    	    	ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+headpath, mIvPhotoView,SpiceApplication.getInstance().options);
				ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix+headpath, mIvPhotoView,SpiceApplication.getInstance().options);
	    	    else
	    	    	mIvPhotoView.setImageResource(R.drawable.empty_photo4);
				break;
			case SEND:
//				mImageFetcher.loadImage(myheadimg, mIvPhotoView);
//				message_tv_nickname.setText(myusername);
				if(mMsgText.getBareJid().indexOf("@1")==-1){
//					try{
//						headpath = "data/avatar/"+avatar_file(Integer.parseInt(StringUtils.parseName(mMsgText.getBareJid())),"middle","");
//	        		}catch(Exception e){
//	        			e.printStackTrace();
//	        		}
//					if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()))!=null){
//						headpath = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getAvatarPath();
//						if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName()!=null &&tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName().length()!=0)
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName());
//						else
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getUsername());
//					}else{
//						headpath = "";
//						message_tv_nickname.setText(StringUtils.parseBareAddress(mMsgText.getBareJid()));//"空"+
//					}
					
					tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()));
					if(tg!=null){
						headpath = tg.getAvatarPath();
//						Toast toast = Toast.makeText(mContext, "我的tg="+tg.toXML()+"头像avatar="+tg.getAvatar()+";avatarpath="+tg.getAvatarPath(), Toast.LENGTH_LONG);
//			    	    toast.show();
						if(tg.getName()!=null && tg.getName().length()!=0)
							message_tv_nickname.setText(tg.getName());
						else
							message_tv_nickname.setText(tg.getUsername());
					}else{
						headpath = "";
						message_tv_nickname.setText(StringUtils.parseBareAddress(mMsgText.getBareJid()));//"空"+
					}
				}else{
					String key = StringUtils.parseResource(mMsgText.getBareJid());
					if(key!=null && key.startsWith("/"))
						key = key.substring(1);//"/18901203590"
//					try{
//						headpath = "data/avatar/"+avatar_file(Integer.parseInt(key),"middle","");
//	        		}catch(Exception e){
//	        			e.printStackTrace();
//	        		}
////					message_tv_nickname.setText("uid为"+key);
////					message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress("2@0")).getName());
//					if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"))!=null){
//						headpath = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getAvatarPath();
//						if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName()!=null && tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName().length()!=0)
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName());//bug 需要登录成功后将自己的信息存入本地数据库
//						else
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getUsername());
//					}else{
//						headpath = "";
//						message_tv_nickname.setText(key+"@0");
//					}
					
					tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"));
					if(tg!=null){
						headpath = tg.getAvatarPath();
						if(tg.getName()!=null && tg.getName().length()!=0)
							message_tv_nickname.setText(tg.getName());
						else
							message_tv_nickname.setText(tg.getUsername());
					}else{
						headpath = "";
						message_tv_nickname.setText(StringUtils.parseBareAddress(key+"@0"));//"空"+
					}
				}
//				mImageFetcher.loadImage(XmppConnectionAdapter.downloadPrefix+headpath, mIvPhotoView);
				if(headpath!=null
	    	    		&& headpath.length()!=0
	    	    		&& !headpath.equalsIgnoreCase("null"))
//	    	    	ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+headpath, mIvPhotoView,SpiceApplication.getInstance().options);
				ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix+headpath, mIvPhotoView,SpiceApplication.getInstance().options);
	    	    else
	    	    	mIvPhotoView.setImageResource(R.drawable.empty_photo4);
				break;
			case conference:
				Log.e("※※※※※2014080508050805※※※※※", "※※fromAccount="+fromAccount+";toAccount="+toAccount);
//				if(mMsgText.getBareJid().indexOf("@conference.")==-1){//自己发给群
//					mImageFetcher.loadImage(myheadimg, mIvPhotoView);
//					message_tv_nickname.setText(myusername);
//				}else{
//					String key = StringUtils.parseResource(mMsgText.getBareJid());
//					if(key.startsWith("/"))
//						key = key.substring(1);//"/18901203590"
//					String key2 = StringUtils.parseName(fromAccount);
//					if(key.equals(key2)){//自己发给群
//						mImageFetcher.loadImage(myheadimg, mIvPhotoView);
//						message_tv_nickname.setText(myusername);
//					}else{
////						Contact contact = mActivity.mListContact.get(key);
////						String url = "";
////						if(contact!=null){
////							message_tv_nickname.setText(contact.getName());
////				            if(contact.getAvatarId()!=null 
////				            		&& contact.getAvatarId().length()!=0 
////				            		&& !contact.getAvatarId().equalsIgnoreCase("null")
////				            		&& (
////				            				contact.getAvatarId().toLowerCase().endsWith(".jpg")
////				            				|| contact.getAvatarId().toLowerCase().endsWith(".png")
////				            				|| contact.getAvatarId().toLowerCase().endsWith(".bmp")
////				            				|| contact.getAvatarId().toLowerCase().endsWith(".gif")
////				            			))
////				            	url = XmppConnectionAdapter.downloadPrefix+StringUtils.parseName(contact.getJID())+"/"+"thumbnail_"+contact.getAvatarId();
////						}
////						if(url!=null && url.length()!=0)
////							mImageFetcher.loadImage(url, mIvPhotoView);
//						mImageFetcher.loadImage(headimg, mIvPhotoView);
//						message_tv_nickname.setText(username);
//					}
//				}
				if(mMsgText.getBareJid().indexOf("@1")==-1){//自己发给群
////					mImageFetcher.loadImage(myheadimg, mIvPhotoView);
////					message_tv_nickname.setText(myusername);
//					try{
//						headpath = "data/avatar/"+avatar_file(Integer.parseInt(StringUtils.parseName(mMsgText.getBareJid())),"middle","");
//	        		}catch(Exception e){
//	        			e.printStackTrace();
//	        		}
//					if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()))!=null){
//						headpath = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getAvatarPath();
//						if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName()!=null)
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName());
//					}else{
//						headpath = "";
//						message_tv_nickname.setText(mMsgText.getBareJid());
//					}
					
					tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()));
					if(tg!=null){
						headpath = tg.getAvatarPath();
//						Toast toast = Toast.makeText(mContext, "我的tg="+tg.toXML()+"头像avatar="+tg.getAvatar()+";avatarpath="+tg.getAvatarPath(), Toast.LENGTH_LONG);
//			    	    toast.show();
						if(tg.getName()!=null && tg.getName().length()!=0)
							message_tv_nickname.setText(tg.getName());
						else
							message_tv_nickname.setText(tg.getUsername());
					}else{
						headpath = "";
						message_tv_nickname.setText(StringUtils.parseBareAddress(mMsgText.getBareJid()));//"空"+
					}
				}else{
					String key = StringUtils.parseResource(mMsgText.getBareJid());
					if(key!=null && key.startsWith("/"))
						key = key.substring(1);//"/18901203590"
//					try{
//						headpath = "data/avatar/"+avatar_file(Integer.parseInt(key),"middle","");
//	        		}catch(Exception e){
//	        			e.printStackTrace();
//	        		}
					String key2 = StringUtils.parseName(fromAccount);
					if(key.equals(key2)){//自己发给群
////						mImageFetcher.loadImage(myheadimg, mIvPhotoView);
////						message_tv_nickname.setText(myusername);
////						message_tv_nickname.setText("uid为"+key);
//						if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"))!=null){
//							headpath = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getAvatarPath();
//							if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName()!=null && tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName().length()!=0)
//								message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName());//bug 需要登录成功后将自己的信息存入本地数据库
//							else
//								message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getUsername());
//						}else{
//							headpath = "";
//							message_tv_nickname.setText(key+"@0");
//						}
						
						tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"));
						if(tg!=null){
							headpath = tg.getAvatarPath();
							if(tg.getName()!=null && tg.getName().length()!=0)
								message_tv_nickname.setText(tg.getName());
							else
								message_tv_nickname.setText(tg.getUsername());
						}else{
							headpath = "";
							message_tv_nickname.setText(StringUtils.parseBareAddress(key+"@0"));//"空"+
						}
					}else{
////						Contact contact = mActivity.mListContact.get(key);
////						String url = "";
////						if(contact!=null){
////							message_tv_nickname.setText(contact.getName());
////				            if(contact.getAvatarId()!=null 
////				            		&& contact.getAvatarId().length()!=0 
////				            		&& !contact.getAvatarId().equalsIgnoreCase("null")
////				            		&& (
////				            				contact.getAvatarId().toLowerCase().endsWith(".jpg")
////				            				|| contact.getAvatarId().toLowerCase().endsWith(".png")
////				            				|| contact.getAvatarId().toLowerCase().endsWith(".bmp")
////				            				|| contact.getAvatarId().toLowerCase().endsWith(".gif")
////				            			))
////				            	url = XmppConnectionAdapter.downloadPrefix+StringUtils.parseName(contact.getJID())+"/"+"thumbnail_"+contact.getAvatarId();
////				            if(url!=null && url.length()!=0)
////								mImageFetcher.loadImage(url, mIvPhotoView);
////						}else{
////							mImageFetcher.loadImage(headimg, mIvPhotoView);
////							message_tv_nickname.setText(username);
//							if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"))!=null){
//								headpath = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getAvatarPath();
//								if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName()!=null
//										&& tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName().length()!=0
//										&& !tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName().equalsIgnoreCase("null"))
//									message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName());
//								else
//									message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getUsername());
//							}else{
//								headpath = "";
//								message_tv_nickname.setText(key+"@0");
//							}
////							message_tv_nickname.setText(key);
////						}
////						if(url!=null && url.length()!=0)
////							mImageFetcher.loadImage(url, mIvPhotoView);
						
						
						tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"));
						if(tg!=null){
							headpath = tg.getAvatarPath();
							if(tg.getName()!=null && tg.getName().length()!=0 && !tg.getName().equalsIgnoreCase("null"))
								message_tv_nickname.setText(tg.getName());
							else
								message_tv_nickname.setText(tg.getUsername());
						}else{
							headpath = "";
							message_tv_nickname.setText(StringUtils.parseBareAddress(key+"@0"));//"空"+
						}
					}
				}
//				mImageFetcher.loadImage(XmppConnectionAdapter.downloadPrefix+headpath, mIvPhotoView);
				if(headpath!=null
	    	    		&& headpath.length()!=0
	    	    		&& !headpath.equalsIgnoreCase("null"))
//	    	    	ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+headpath, mIvPhotoView,SpiceApplication.getInstance().options);
				ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix+headpath, mIvPhotoView,SpiceApplication.getInstance().options);
	    	    else
	    	    	mIvPhotoView.setImageResource(R.drawable.empty_photo4);
				break;
		
		}
		
		message_tv_timestamp.setText(mMsgText.getTimestamp().toLocaleString());
//		mBitmap = PhotoUtils.getBitmapFromFile(getMessage());/////////
//		try{
//			mBitmap = getHttpImage("http://10.0.2.2:8080/thumbnail_e33455fc-da75-44f8-ab91-605f8bbcac97.jpg");
//			
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//		mImageFetcher.loadRoundImage("http://10.0.2.2:8080/thumbnail_e33455fc-da75-44f8-ab91-605f8bbcac97.jpg", mIvImage,mHandler);
//		mHandler.sendEmptyMessage(0);
		if(mRecordPath.startsWith("http://")){
        	String filename = mRecordPath.substring(mRecordPath.lastIndexOf("/"));
        	tempdownsavepath = setMkdir(PHOTOPATH2)+filename;
        	if(!mMsgText.getIsDownload())
        	downloadMethod(mRecordPath,tempdownsavepath);
//			mHandler.sendEmptyMessage(0);
        	mRecordPath = tempdownsavepath;
//        	Toast.makeText(mContext, "视频222"+mRecordPath, Toast.LENGTH_SHORT).show(); 
		}else if(!mMsgText.getIsUpload() && chattype!=2){//upload
            final File file = new File(mRecordPath);  
            
            if (file != null) {  
//                String request = UploadUtil.uploadFile(file, requestURL);  
//                String uploadHost="http://10.0.2.2:9090/plugins/offlinefiletransfer/offlinefiletransfer";  
            	String uploadHost = XmppConnectionAdapter.uploadHost;
//                RequestParams params=new RequestParams();  
////                params.addBodyParameter("msg",imgtxt.getText().toString());   
//                params.addBodyParameter(picPath.replace("/", ""), file);   
//                uploadMethod(params,uploadHost);
////                uploadImage.setText(request);  
                RequestParams params = new RequestParams();
//                params.addHeader("name", "value");
//                params.addQueryStringParameter("name", "value");
                params.addQueryStringParameter("fromAccount", fromAccount);
                params.addQueryStringParameter("toAccount", toAccount);
                if(mGroupMsgRecipient!=null){
                	StringBuffer sb = new StringBuffer();
                	for(int p=0;p<mGroupMsgRecipient.size();p++){
                		sb.append(mGroupMsgRecipient.get(p)+"|");
                		Log.e("※※※※※20141228群发消息接收人 ImageMessageItem start※※※※※", "※※群发消息接收人start jidwithres="+(String)mGroupMsgRecipient.get(p));
                	}
                	params.addQueryStringParameter("mGroupMsgRecipient", sb.toString());
                	Log.e("※※※※※20141228群发消息接收人 ImageMessageItem end※※※※※", "※※群发消息接收人"+sb.toString());
                }
                params.addQueryStringParameter("sendType", "video");
                params.addQueryStringParameter("sendSize", (int) mRecord_Time+"");
                // 只包含字符串参数时默认使用BodyParamsEntity，
                // 类似于UrlEncodedFormEntity（"application/x-www-form-urlencoded"）。
//                params.addBodyParameter("fromAccount", fromAccount);
//                params.addBodyParameter("toAccount", toAccount);
//                params.addBodyParameter("sendType", "audio");
//                params.addBodyParameter("sendSize", (int) mRecord_Time+"");

                // 加入文件参数后默认使用MultipartEntity（"multipart/form-data"），
                // 如需"multipart/related"，xUtils中提供的MultipartEntity支持设置subType为"related"。
                // 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity（如：
                // MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity）。
                // 例如发送json参数：params.setBodyEntity(new StringEntity(jsonStr,charset));
//                BodyParamsEntity bpe = new BodyParamsEntity();
//                bpe.addParameter("fromAccount", fromAccount);
//                bpe.addParameter("toAccount", toAccount);
//                bpe.addParameter("sendType", "audio");
//                bpe.addParameter("sendSize", (int) mRecord_Time+"");
//                params.setBodyEntity(bpe);
                params.addBodyParameter("file", file);
                uploadMethod(params,uploadHost);
                
            }  
		}
	}
	@Override
	public void onClick(View v) {
//		Intent intent = new Intent(mContext, ImageBrowserActivity.class);
//		intent.putExtra(ImageBrowserActivity.IMAGE_TYPE,
//				ImageBrowserActivity.TYPE_PHOTO);
////		intent.putExtra("path", getMessage());//消息内容
//		intent.putExtra("path", "e33455fc-da75-44f8-ab91-605f8bbcac97.jpg");
//		mContext.startActivity(intent);
//		((ChatPullRefListActivity) mContext).overridePendingTransition(R.anim.zoom_enter,
//				0);
		
		Intent playIntent=new Intent(mContext, VideoPlayer.class);
		String pathString=mRecordPath;
//		Toast.makeText(mContext, "视频333"+mRecordPath, Toast.LENGTH_SHORT).show(); 
		playIntent.putExtra("path", pathString);
		if(mActivity != null)
			((ChatPullRefListActivity) mContext).startActivity(playIntent);
		
	}

	@Override
	public boolean onLongClick(View v) {
		if(mDialog!=null)
			mDialog.show();
		return true;
	}
	

	public View getRootView() {
		return mRootView;
	}
	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				startLoadingAnimation();
				break;

			case 1:
				updateLoadingProgress(msg.arg1);
				break;

			case 2:
				stopLoadingAnimation();
//				Toast.makeText(mContext, "下载成功"+mRecordPath, Toast.LENGTH_SHORT).show(); 
				if(mMsgText.getIsOffline()==2){
//					mRootView.findViewById(R.id.isOfflineMsg).setVisibility(View.VISIBLE);
					
				    if(message_tv_status_audio!=null){
				    	message_tv_status_audio.setBackgroundResource(R.drawable.bg_msgbox_state_failure2);
				    	message_tv_status_audio.setText("发送失败");
				    }
				}else if(mMsgText.getIsOffline()==1){
//					mRootView.findViewById(R.id.isOfflineMsg).setVisibility(View.GONE);
				    if(message_tv_status_audio!=null){
				    	message_tv_status_audio.setBackgroundResource(R.drawable.bg_msgbox_state_read2);
				    	message_tv_status_audio.setText("送达");
				    }
				}else{//20200315 增加，修正一直显示“发送中”的bug
					if(message_tv_status_audio!=null){
				    	message_tv_status_audio.setBackgroundResource(R.drawable.bg_msgbox_state_failure2);
				    	message_tv_status_audio.setText("发送失败");
				    }
				}
				break;
			case 3:
				if(mStAdapter!=null){
					mStAdapter.deleteMsg(mPosition);
					mStAdapter.notifyDataSetChanged();
				}
				break;
			}
		}

	};
	private void startLoadingAnimation() {
		if (mAnimation != null) {
			mAnimation.stop();
			mAnimation = null;
		}
		mAnimation = new AnimationDrawable();
		mAnimation.addFrame(getDrawable(R.drawable.ic_loading_msgplus_01), 300);
		mAnimation.addFrame(getDrawable(R.drawable.ic_loading_msgplus_02), 300);
		mAnimation.addFrame(getDrawable(R.drawable.ic_loading_msgplus_03), 300);
		mAnimation.addFrame(getDrawable(R.drawable.ic_loading_msgplus_04), 300);
		mAnimation.setOneShot(false);
//		mIvImage.setVisibility(View.GONE);
		mLayoutLoading.setVisibility(View.VISIBLE);
		mIvLoading.setVisibility(View.VISIBLE);
		mHtvLoadingText.setVisibility(View.VISIBLE);
//		mIvLoading.setImageDrawable(mAnimation);
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				try{
					if(mAnimation != null)
						mAnimation.start();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});
		mHandler.sendEmptyMessage(1);
	}

	private void stopLoadingAnimation() {
		if (mAnimation != null) {
			mAnimation.stop();
			mAnimation = null;
		}
		mLayoutLoading.setVisibility(View.GONE);
		mHtvLoadingText.setVisibility(View.GONE);
//		mIvImage.setVisibility(View.VISIBLE);
//		if (mBitmap != null) {
//			mIvImage.setImageBitmap(mBitmap);
//		}
	}

	private void updateLoadingProgress(int progress) {
		mProgress = progress;
		if (mProgress < 100) {
//			mProgress++;
			mHtvLoadingText.setText(mProgress + "%");
//			mHandler.sendEmptyMessageDelayed(1, 100);
		} else {
			mProgress = 0;
			mHandler.sendEmptyMessage(2);
		}
	}
	@SuppressWarnings("deprecation")
	private Drawable getDrawable(int id) {
		return new BitmapDrawable(BitmapFactory.decodeResource(
				mContext.getResources(), id));
	}
	
	//"/sdcard/httpcomponents-client-4.2.5-src.zip"
	public  void downloadMethod(String url,String savetarget){
    	http = new HttpUtils();
//    	http.configCurrentHttpCacheExpiry(1000 * 10); // 设置缓存10秒，10秒内直接返回上次成功请求的结果。
    	handler = http.download(url,
    			savetarget,
    		    true, // 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
    		    true, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
    		    new RequestCallBack<File>() {

    		        @Override
    		        public void onStart() {
//    		            testTextView.setText("conn...");
    		            mHandler.sendEmptyMessage(0);
    		        }

    		        @Override
    		        public void onLoading(long total, long current, boolean isUploading) {
//    		            testTextView.setText("download: "+current + "/" + total);
    					android.os.Message message = mHandler.obtainMessage();
    					message.arg1 = (int) (current);
    					message.what = 1;
    		//								message.sendToTarget();
    					mHandler.sendMessage(message);
    		        }

    		        @Override
    		        public void onSuccess(ResponseInfo<File> responseInfo) {
    		        	//statuscode == 200
//    		            testTextView.setText("statuscode:"+responseInfo.statusCode+";downloaded:" + responseInfo.result.getPath());
//    		        	mRecordPath=tempdownsavepath;
    		        	mHandler.sendEmptyMessage(2);
    		        	if(mStAdapter!=null)
    		        		mStAdapter.update(mPosition, false, true,1);
    		        	Log.e("※※※※※下载成功下载成功下载成功※※※※※", "※※下载成功※※");
    		        }


    		        @Override
    		        public void onFailure(HttpException error, String msg) {
    		        	if(error.getExceptionCode()==416){
    		        		if(mStAdapter!=null)
    		        			mStAdapter.update(mPosition, false, true,2);
    		        	}
//    		        	else
//    		        		mDisplayVoicePlay.setClickable(false);//下载失败，不可点击
//    		        	if(error.getExceptionCode()==416)
//    		        		testTextView.setText("已下载，无须重复下载"+";Error:"+msg);
//    		        	else
//    		        		testTextView.setText("errorcode:"+error.getExceptionCode()+";Error:"+msg);
    		        	mHandler.sendEmptyMessage(2);
    		        	Log.e("※※※※※下载失败下载失败下载失败※※※※※", "※※下载失败※※"+error.getMessage());
    		        }
    		});
    }
    public void stopDownloadMethod(){
    	//调用stop()方法停止下载
//    	handler.stop();
    	handler.cancel();
    }
    
    public  void uploadMethod(final RequestParams params,final String uploadHost) {  
    	http = new HttpUtils();
    	http.configCurrentHttpCacheExpiry(1000 * 10); // 设置缓存10秒，10秒内直接返回上次成功请求的结果。
    	handler = http.send(HttpRequest.HttpMethod.POST, uploadHost, params,new RequestCallBack<String>() {  
                    @Override  
                    public void onStart() {  
//                      msgTextview.setText("conn...");  
                      mHandler.sendEmptyMessage(0);
                    }  
                    @Override  
                    public void onLoading(long total, long current,boolean isUploading) {  
//                        if (isUploading) {  
//                          msgTextview.setText("upload: " + current + "/"+ total);  
//                        } else {  
//                          msgTextview.setText("reply: " + current + "/"+ total);  
//                        }  
    					android.os.Message message = mHandler.obtainMessage();
//    					message.arg1 = (int) (current*100/total);
    					message.arg1 = 80;//gzip 后 total为0
    					message.what = 1;
    		//								message.sendToTarget();
    					mHandler.sendMessage(message);
                    }  
                    public void onSuccess(ResponseInfo<String> responseInfo) { 
                    	//statuscode == 200
//                      msgTextview.setText("statuscode:"+responseInfo.statusCode+";reply: " + responseInfo.result); 
                    	mMsgText.setIsOffline(1);
                    	mHandler.sendEmptyMessage(2);
                    	if(mStAdapter!=null)
                    		mStAdapter.update(mPosition, true, false,1);
                    }  
                    public void onFailure(HttpException error, String msg) {  
//                      msgTextview.setText(error.getExceptionCode() + ":" + msg);  
                    	Log.e("※※※※※20140301※※※※※", "※※上传失败"+error.getExceptionCode() + ":" + msg);
                    	mMsgText.setIsOffline(2);
                    	mHandler.sendEmptyMessage(2);
                    	if(mStAdapter!=null)
                    		mStAdapter.update(mPosition, true, false,2);
                    }  
                });  
        
    } 
    
    /** 
     * 检验SDcard状态 
     * @return boolean 
     */  
    public boolean checkSDCard()  
    {  
        if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))  
        {  
            return true;  
        }else{  
            return false;  
        }  
    }
    /** 
     * 保存文件文件到目录 
     * @param context 
     * @return  文件保存的目录 
     */  
    public String setMkdir(String myrelativefilepath)  
    {  
        String filePath;  
        if(checkSDCard())  
        {  
//            filePath = Environment.getExternalStorageDirectory()+File.separator+"myfilepath"; 
            filePath = Environment.getExternalStorageDirectory()+File.separator+myrelativefilepath+File.separator;
        }else{  
//            filePath = context.getCacheDir().getAbsolutePath()+File.separator+"myfilepath";  
            filePath = mContext.getCacheDir().getAbsolutePath()+File.separator+myrelativefilepath+File.separator; 
        }  
        //下载文件到应用的文件目录,这样就可以实现再没有sd卡的条件下也可以顺利的下载
//        filePath = mContext.getApplicationContext().getFilesDir().getAbsolutePath() + File.separator+myrelativefilepath+File.separator; 
        
        File file = new File(filePath);  
        if(!file.exists())  
        {  
            boolean b = file.mkdirs();  
//            Log.e("file", "文件不存在  创建文件    "+b);  
        }else{  
//            Log.e("file", "文件存在");  
        }  
        return filePath;  
    }
    
	public void initNameImg(){
		switch (messageType) {
			case RECEIVER:
				if(headimg==null
						|| headimg.equalsIgnoreCase("null")
						|| headimg.length()==0
						|| username==null
						|| username.equalsIgnoreCase("null")
						|| username.length()==0){
					duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(mMsgText.getBareJid()));//toAccount
					if(duitangInfo!=null){
						headimg = duitangInfo.getIsrc();
						username = duitangInfo.getName();
					}else{
						headimg = "";
						username = StringUtils.parseName(mMsgText.getBareJid());
					}
				}
//				if(myheadimg==null
//						|| myheadimg.equalsIgnoreCase("null")
//						|| myheadimg.length()==0
//						|| myusername==null
//						|| myusername.equalsIgnoreCase("null")
//						|| myusername.length()==0){
//					duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(fromAccount));
//					if(duitangInfo!=null){
//						myheadimg = duitangInfo.getIsrc();
//						myusername = duitangInfo.getName();
//					}else{
//						myheadimg = "";
//						myusername = StringUtils.parseName(fromAccount);
//					}
//				}
				break;
			case SEND:
//				if(headimg==null
//						|| headimg.equalsIgnoreCase("null")
//						|| headimg.length()==0
//						|| username==null
//						|| username.equalsIgnoreCase("null")
//						|| username.length()==0){
//					duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(fromAccount));
//					if(duitangInfo!=null){
//						headimg = duitangInfo.getIsrc();
//						username = duitangInfo.getName();
//					}else{
//						headimg = "";
//						username = StringUtils.parseName(fromAccount);
//					}
//				}
				if(myheadimg==null
						|| myheadimg.equalsIgnoreCase("null")
						|| myheadimg.length()==0
						|| myusername==null
						|| myusername.equalsIgnoreCase("null")
						|| myusername.length()==0){
					if(mMsgText.getBareJid().equalsIgnoreCase("Me"))
						duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(fromAccount));
					else
						duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(mMsgText.getBareJid()));
					if(duitangInfo!=null){
						myheadimg = duitangInfo.getIsrc();
						myusername = duitangInfo.getName();
					}else{
						myheadimg = "";
						if(mMsgText.getBareJid().equalsIgnoreCase("Me"))
							myusername = StringUtils.parseName(fromAccount);
						else
							myusername = StringUtils.parseName(mMsgText.getBareJid());//toAccount
					}
				}
				break;
			case conference:
				if(mMsgText.getBareJid().indexOf("@conference.")==-1){//自己发给群
					if(myheadimg==null
							|| myheadimg.equalsIgnoreCase("null")
							|| myheadimg.length()==0
							|| myusername==null
							|| myusername.equalsIgnoreCase("null")
							|| myusername.length()==0){
						if(mMsgText.getBareJid().equalsIgnoreCase("Me"))
							duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(fromAccount));
						else
							duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(mMsgText.getBareJid()));
						if(duitangInfo!=null){
							myheadimg = duitangInfo.getIsrc();
							myusername = duitangInfo.getName();
						}else{
							myheadimg = "";
							if(mMsgText.getBareJid().equalsIgnoreCase("Me"))
								myusername = StringUtils.parseName(fromAccount);
							else
								myusername = StringUtils.parseName(mMsgText.getBareJid());
						}
					}
				}else{
					String key = StringUtils.parseResource(mMsgText.getBareJid());
					if(key!=null && key.startsWith("/"))
						key = key.substring(1);//"/18901203590"
					String key2 = StringUtils.parseName(fromAccount);
					if(key.equals(key2)){//自己发给群
						if(myheadimg==null
								|| myheadimg.equalsIgnoreCase("null")
								|| myheadimg.length()==0
								|| myusername==null
								|| myusername.equalsIgnoreCase("null")
								|| myusername.length()==0){
							duitangInfo = duitangInfoAdapter.getDuitangInfo(key);
							if(duitangInfo!=null){
								myheadimg = duitangInfo.getIsrc();
								myusername = duitangInfo.getName();
							}else{
								myheadimg = "";
								myusername = key;
							}
						}
					}else{
						//message_send_template.xml
						if(headimg==null
								|| headimg.equalsIgnoreCase("null")
								|| headimg.length()==0
								|| username==null
								|| username.equalsIgnoreCase("null")
								|| username.length()==0){
							duitangInfo = duitangInfoAdapter.getDuitangInfo(key);
							if(duitangInfo!=null){
								headimg = duitangInfo.getIsrc();
								username = duitangInfo.getName();
							}else{
								headimg = "";
								username = key;
							}
						}
					}
				}
				
//				Log.e("※※※※※20141020※※※※※", "※※消息TextMessageItem=>mMsgText.getBareJid()="
//						+mMsgText.getBareJid()
//						+";mMsgText.getMTo()="
//						+mMsgText.getMTo()
//						+";key="
//						+StringUtils.parseResource(mMsgText.getBareJid())
//						+";key2="
//						+StringUtils.parseName(fromAccount));
				break;
			default:
				break;
		
		}
	}

	
	
	private class OnReplyDialogItemClickListener implements
	onSimpleListItemClickListener {
		
		public OnReplyDialogItemClickListener() {
		}
		@Override
		public void onItemClick(int position) {
			// "复制","删除","转发" };//分享,翻译
			switch (position) {
				case 0:
					copy(mMsgText.getMessage());
					break;
				case 1:
					startDelete();
					break;
				case 2:
//					ClipboardManager m = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
//					m.setText(mMsgText.getMessage());
//		        	Intent intent = new Intent(mContext, BulkMsgContactListPullRefListActivity.class);//BulkMsgContactListPullRefListActivity
//		        	intent.putExtra("myheadimg", myheadimg);
//		        	intent.putExtra("myusername", myusername);
//		        	
//		        	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		        	mContext.startActivity(intent);
//		        	if(mActivity != null)
//		        		((ChatPullRefListActivity)mContext).finish();
//		        	else if(mActivity_bulkmsg !=null)
//		        		((BulkMsgChatPullRefListActivity)mContext).finish();
					break;
			}
		}
	}
	private void copy(String text) {
		ClipboardManager m = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
		m.setText(text);
		showCustomToast("已成功复制文本:"+text);
	}
	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(mContext).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(mContext);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
	
	private static ExecutorService LIMITED_TASK_EXECUTOR;
    static {
      LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7); 
    }; 
	protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected FlippingLoadingDialog mLoadingDialog;
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
//		mAsyncTasks.add(asyncTask.execute());
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
	}

	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}

	protected void showLoadingDialog(String text) {
		if (text != null) {
			mLoadingDialog.setText(text);
		}
		mLoadingDialog.show();
	}

	protected void dismissLoadingDialog() {
		if (mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}
	private void startDelete() {
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showLoadingDialog("正在删除,请稍候...");
				Log.e("MMMMMMMMMMMM20141224DeleteMessageMMMMMMMMMMMM", "++++++++++++++20141224DeleteMessage="+mMsgText.getId());
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {
				    messageAdapter.deleteMessage(mMsgText.getId());
				} catch (Exception e) {
				    Log.e(TAG, e.getMessage());
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				dismissLoadingDialog();
				if (!result) {
					showCustomToast("删除失败...");
				}else{
					showCustomToast("删除成功...");
					mHandler.sendEmptyMessage(3);
				}
				
				
			}

		});
	}
	
	public String sprintf(String format, double number) {
		return new DecimalFormat(format).format(number);
	}
	//sizeType :big,middle,small
	//type : real 或 ""
	public String avatar_file(int uid, String sizeType, String type) {
		String var = "avatarfile_" + uid + "_" + sizeType + "_" + type;
		String avatarPath = "";
			uid = Math.abs(uid);
			String struid = sprintf("000000000", uid);
			String dir1 = struid.substring(0, 3);
			String dir2 = struid.substring(3, 5);
			String dir3 = struid.substring(5, 7);
			StringBuffer avater = new StringBuffer();
			avater.append(dir1 + "/" + dir2 + "/" + dir3 + "/" + struid.substring(struid.length() - 2));
			avater.append("real".equals(type) ? "_real_avatar_" : "_avatar_");
			avater.append(sizeType + ".jpg");
			avatarPath = avater.toString();

		return avatarPath;
	}
}

